

import ikelib.FileDropTarget;
import ikelib.wintime;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;

import javax.swing.JComboBox;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.JList;
import javax.swing.AbstractListModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;



import java.awt.Rectangle;
import javax.swing.UIManager;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.BoxLayout;

import wcg.ImportData;
import wcg.WinImporter;

import java.awt.GridLayout;





public class CsvImportDlg extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTextField textFieldCSVFile;
	public  ActionListener Parent=null;	// actionlistener型の親
	public  JButton ButtonImport=null;	
	private String ConfFile=null;		// CSVの設定ファイル
	private String OutDir=null;			// 出力ディレクトリ
	private String OutFile=null;		// 出力ファイル（dir + file)
	
	
	JComboBox comboBoxConfig=null;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			CsvImportDlg dialog = new CsvImportDlg();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	CsvImportParameter Param=null;
	private void onLoadConfFile(){
		if(Param.load(ConfFile)){
			String cursel = (String)comboBoxConfig.getSelectedItem();
			String [] name = Param.getConfName();
			if(name.length>0){
				comboBoxConfig.removeAllItems();
				for(int i=0;i<name.length;i++){
					comboBoxConfig.addItem(name[i]);
				}
				comboBoxConfig.setSelectedItem(cursel);
				if(comboBoxConfig.getSelectedIndex()<0){
					comboBoxConfig.setSelectedIndex(0);
				}
			}
		}
	}
	public boolean LoadConfFile(String conf){
		ConfFile = conf;
		onLoadConfFile();
		return true;
	}
	public boolean SetOutDir(String dir){
		OutDir = dir;
		return true;
	}
	public String GetOutFile(){
		return OutFile;
	}
	/*
	 * コンフィグレーションが変化したとき
	 */
	private void onConfigSelectChanged() {
		String cur = (String)comboBoxConfig.getSelectedItem();
		CsvImportParameter.CsvImportConfigElement conf = Param.getConfig(cur);
		if(conf==null) return;
		String view = Param.getConfigAsText(cur);
		textPaneConfigPreview.setText(view );
		if(conf.DateColumn>=0){
			textFieldStartTime.setEditable(false);
			textFieldIntervalSec.setEditable(false);
		}
		else{
			if(conf.IntervalColumn>=0){
				textFieldStartTime.setEditable(true);
				textFieldIntervalSec.setEditable(false);
			}
			else{
				textFieldStartTime.setEditable(true);
				textFieldIntervalSec.setEditable(true);
			}
		}
	
		textFieldSamplerate.setText(String.valueOf(conf.SampleRate));
		textFieldIgnoreHeader.setText(String.valueOf(conf.IgnoreHeader));
		textFieldDateField.setText(String.valueOf(conf.DateColumn));
		textFieldTimeOffsetField.setText(String.valueOf(conf.IntervalColumn));
		
		
		DefaultTableModel md =  (DefaultTableModel) TableChannel.getModel();
		md.setRowCount(0);
		LinkedList<CsvImportParameter.CsvImportFieldElement>  lst = Param.getFieldElement(cur);
		Iterator<CsvImportParameter.CsvImportFieldElement> ite = lst.iterator();
		while(ite.hasNext()){
			CsvImportParameter.CsvImportFieldElement p = ite.next();
			String[] data = new String[3];
			data[0] = String.format("%04x", p.Chid);
			data[1] = String.valueOf(p.Column);
			data[2] = String.valueOf(p.Factor);
			md.addRow(data);
		}
		
	}
	// ch idなオブジェクトの配列を返す。
	private Object[] getTablevalue(int chid){
		DefaultTableModel md =  (DefaultTableModel) TableChannel.getModel();
		int row = md.getRowCount();
		int col = md.getColumnCount();
		Object[] ret = null; 
		for(int i=0;i<row;i++){
			String id = (String)md.getValueAt(i,0);
			if(Integer.valueOf(id,16) == chid){
				ret = new Object[col];
				for(int j=0;j<col;j++){
					ret[j] = md.getValueAt(i,j);
				}
			}
		}
		return ret;
	}
	/*
	 * テーブルからCH IDの配列を返す
	 */
	private int[] getTableId(){
		DefaultTableModel md =  (DefaultTableModel) TableChannel.getModel();
		int row = md.getRowCount();
		int col = md.getColumnCount();
		int[] ret = new int[row]; 
		for(int i=0;i<row;i++){
			String id = (String)md.getValueAt(i,0);
			ret[i] = Integer.valueOf(id,16);
		}
		return ret;
		
	}
	private void onTableAdd(){
		DefaultTableModel md =  (DefaultTableModel) TableChannel.getModel();
		int c = md.getRowCount();
		String[] data = new String[3];
		int id = 0xffff;
		int cc  = 1;
		double dd = 1.0;
		if(c>=1){
			String s = (String)md.getValueAt(c-1,0);
			if(s!=null){
				id = Integer.valueOf(s,16);
				id++;
			}
			s = (String)md.getValueAt(c-1,1);
			if(s!=null){
				cc = Integer.valueOf(s);
				cc ++;
			}
			s = (String)md.getValueAt(c-1,2);
			if(s!=null){
				dd = Double.valueOf(s);
			}
		}
		data[0] = String.format("%04x", id);
		data[1] = String.valueOf(cc);
		data[2] = String.valueOf(dd);
		md.addRow(data);
	}
	private void onTableDel(){
		DefaultTableModel md =  (DefaultTableModel) TableChannel.getModel();
		int c = md.getRowCount();
		if(c>=0) md.removeRow(c-1);
	}
	private void onPreviewCSV()  {
		String file = textFieldCSVFile.getText();
		String s = textFieldIgnoreHeader.getText();
		int ignore = Integer.valueOf(s);
		textPaneCSV.setText(new String());
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;
			String totalline = new String();
			int i=0;
			int count = 0;
			while(null != (line = br.readLine())){
				if(i++<ignore) continue;
				totalline += line + "\n";
				if(count++>3) break;
			}
			br.close();
			textPaneCSV.setText(totalline);
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	JTextPane textPaneConfigPreview=null;
	private JTextField textFieldStartTime;
	private JTextField textFieldIntervalSec;
	private JComboBox comboBoxInterporation;
	private JTextField textFieldIgnoreHeader;
	private JTextField textFieldDateField;
	private JTextField textFieldTimeOffsetField;
	private JTable TableChannel;
	private JTextField textFieldSamplerate;
	private JTextPane textPaneCSV;
	/**
	 * Create the dialog.
	 */
	public CsvImportDlg() {
		setTitle("Import CSV (for Temperature)");
		setBounds(100, 100, 529, 712);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		
		
		String[] chtableColumn = {"CH ID","Index","Factor"};
		DefaultTableModel chtable = new DefaultTableModel(chtableColumn,1);
		
		JPanel panel_CSVFile = new JPanel();
		panel_CSVFile.setBorder(new TitledBorder(null, "CSV file", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_CSVFile.setBounds(10, 435, 492, 198);
		contentPanel.add(panel_CSVFile);
		panel_CSVFile.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_3 = new JPanel();
		panel_CSVFile.add(panel_3, BorderLayout.NORTH);
		panel_3.setBorder(new EmptyBorder(2, 2, 2, 2));
		panel_3.setLayout(new BoxLayout(panel_3, BoxLayout.X_AXIS));
		
		textFieldCSVFile = new JTextField();
		panel_3.add(textFieldCSVFile);
		textFieldCSVFile.setText("Drop file here");
		textFieldCSVFile.setToolTipText("Drop file here");
		textFieldCSVFile.setDropTarget(new FileDropTarget());
		textFieldCSVFile.setColumns(10);
		
		JButton btnOpenCSV = new JButton("...");
		panel_3.add(btnOpenCSV);
		
		JScrollPane scrollPane_2 = new JScrollPane();
		panel_CSVFile.add(scrollPane_2, BorderLayout.CENTER);
		
		textPaneCSV = new JTextPane();
		scrollPane_2.setViewportView(textPaneCSV);
		textPaneCSV.setPreferredSize(new Dimension(1000,300));
		textPaneCSV.setEditable(false);
		
		JButton btnNewButtonPreview = new JButton("Preview");
		btnNewButtonPreview.setToolTipText("Preview CSV file. (Header ignored)");
		scrollPane_2.setColumnHeaderView(btnNewButtonPreview);
		btnNewButtonPreview.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				onPreviewCSV();
			}

		});
		btnOpenCSV.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser filechooser = new JFileChooser();
				if(JFileChooser.APPROVE_OPTION == filechooser.showOpenDialog(null)){
					File f = filechooser.getSelectedFile();
					textFieldCSVFile.setText(f.getAbsolutePath());
				}
			}
		});
		
		JPanel panel_ChannelFieldTop = new JPanel();
		panel_ChannelFieldTop.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Channel Field", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_ChannelFieldTop.setBounds(202, 155, 303, 283);
		contentPanel.add(panel_ChannelFieldTop);
		panel_ChannelFieldTop.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_Channel = new JPanel();
		panel_ChannelFieldTop.add(panel_Channel, BorderLayout.NORTH);
		panel_Channel.setLayout(new GridLayout(5, 2, 0, 0));
		
		JLabel lblSampleRate = new JLabel("Sample rate");
		panel_Channel.add(lblSampleRate);
		
		textFieldSamplerate = new JTextField();
		textFieldSamplerate.setToolTipText("Sample Rate[Hz] ex. 1,100");
		panel_Channel.add(textFieldSamplerate);
		textFieldSamplerate.setText("1");
		textFieldSamplerate.setColumns(10);
		
		JLabel lblIgnoreHeader = new JLabel("Ignore Header");
		panel_Channel.add(lblIgnoreHeader);
		
		textFieldIgnoreHeader = new JTextField();
		textFieldIgnoreHeader.setToolTipText("Number of line(s) to ignore on reading CSV file.");
		panel_Channel.add(textFieldIgnoreHeader);
		textFieldIgnoreHeader.setText("0");
		textFieldIgnoreHeader.setColumns(10);
		
		JLabel lblTimeField = new JLabel("Date field");
		panel_Channel.add(lblTimeField);
		
		textFieldDateField = new JTextField();
		textFieldDateField.setToolTipText("Column number of Date field. 1,2,3... If CSV file doesn't contain Date field, specify negative value. ");
		panel_Channel.add(textFieldDateField);
		textFieldDateField.setText("1");
		textFieldDateField.setColumns(10);
		
		JLabel lblTimeOffsetField = new JLabel("Time Offset Field");
		panel_Channel.add(lblTimeOffsetField);
		
		textFieldTimeOffsetField = new JTextField();
		textFieldTimeOffsetField.setToolTipText("Column of Time Offset. ex. 1,2,... If CSV file doesn' have Time Offset, specify negative.");
		panel_Channel.add(textFieldTimeOffsetField);
		textFieldTimeOffsetField.setText("-1");
		textFieldTimeOffsetField.setColumns(10);
		
		JPanel panel = new JPanel();
		panel_ChannelFieldTop.add(panel, BorderLayout.CENTER);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_Channel_field = new JPanel();
		panel.add(panel_Channel_field, BorderLayout.NORTH);
		panel_Channel_field.setLayout(new GridLayout(0, 3, 0, 0));
		
		JLabel lblChannelField = new JLabel("Channel Field");
		panel_Channel_field.add(lblChannelField);
		
		JButton btnAddChannel = new JButton("+");
		panel_Channel_field.add(btnAddChannel);
		
		JButton btnAddChannelDel = new JButton("-");
		panel_Channel_field.add(btnAddChannelDel);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		panel.add(scrollPane_1, BorderLayout.CENTER);
		
				TableChannel = new JTable(chtable);
				scrollPane_1.setViewportView(TableChannel);
				btnAddChannelDel.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						onTableDel();
					}
				});
				btnAddChannel.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						onTableAdd();
					}
				});
				
				JPanel panel_ConfigField = new JPanel();
				panel_ConfigField.setBorder(new TitledBorder(null, "Config Field", TitledBorder.LEADING, TitledBorder.TOP, null, null));
				panel_ConfigField.setBounds(202, 14, 303, 131);
				contentPanel.add(panel_ConfigField);
				panel_ConfigField.setLayout(new GridLayout(0, 2, 0, 0));
				
				JLabel lblStartTime = new JLabel("Start Time");
				panel_ConfigField.add(lblStartTime);
				
				textFieldStartTime = new JTextField();
				panel_ConfigField.add(textFieldStartTime);
				textFieldStartTime.setText("2013/1/1 12:0:0");
				textFieldStartTime.setToolTipText("2012/12/30 18:59:00 or 2012/12/30 18:59'00 ");
				textFieldStartTime.setColumns(10);
				
				JLabel lblStepsec = new JLabel("Interval [sec]");
				panel_ConfigField.add(lblStepsec);
				
				textFieldIntervalSec = new JTextField();
				panel_ConfigField.add(textFieldIntervalSec);
				textFieldIntervalSec.setToolTipText("IntervalTime is used if CSV file doesn't contain any time or date field.");
				textFieldIntervalSec.setText("60");
				textFieldIntervalSec.setColumns(10);
				
				JLabel lblInterporation = new JLabel("Interporation");
				panel_ConfigField.add(lblInterporation);
				
				comboBoxInterporation = new JComboBox();
				panel_ConfigField.add(comboBoxInterporation);
				comboBoxInterporation.setModel(new DefaultComboBoxModel(new String[] {"Step&Hold","Liner"}));
				comboBoxInterporation.setSelectedIndex(1);
				
				JPanel panel_template = new JPanel();
				panel_template.setBorder(new TitledBorder(null, "Template", TitledBorder.LEADING, TitledBorder.TOP, null, null));
				panel_template.setBounds(10, 14, 185, 419);
				contentPanel.add(panel_template);
				panel_template.setLayout(new BorderLayout(0, 0));
				
				comboBoxConfig = new JComboBox();
				panel_template.add(comboBoxConfig, BorderLayout.NORTH);
				comboBoxConfig.setToolTipText("Select configuration template.  \\nTo modify , add configuration , Please eidt csvconf.ini file.");
				comboBoxConfig.addItemListener(new ItemListener() {
					public void itemStateChanged(ItemEvent arg0) {
						onConfigSelectChanged();
					}

				});
				comboBoxConfig.setSelectedIndex(-1);
				
				textPaneConfigPreview = new JTextPane();
				textPaneConfigPreview.setToolTipText("Preview of csvconf.ini.");
				panel_template.add(textPaneConfigPreview, BorderLayout.CENTER);
				textPaneConfigPreview.setEditable(false);
		
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			
			JPanel panel_4 = new JPanel();
			buttonPane.add(panel_4);
			panel_4.setLayout(new GridLayout(0, 2, 0, 0));
			
			ButtonImport = new JButton("Import");
			panel_4.add(ButtonImport);
			ButtonImport.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					onImport(e );
					setVisible(false);
				}
			});
			{
				JButton okButton = new JButton("Close");
				panel_4.add(okButton);
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						
						setVisible(false);
					}
				});
				okButton.setActionCommand("OK");
				getRootPane().setDefaultButton(okButton);
			}
		}
		Param=new CsvImportParameter();
	}
	
	private void onImport(ActionEvent e){
		if(Parent!=null) {
			Parent.actionPerformed(e);
		}
	}

	private void getConfig(){
		
	}
	private String getCSVFile() {
		String ret = textFieldCSVFile.getText();
		return ret;
	}
	/*
	 * インポートするデータを作成する。
	 */
	private ImportData getImportData() throws NumberFormatException {
		CsvImport tmp=new CsvImport();
		String f = textFieldCSVFile.getText();
		File fl = new File(f);
		if(!fl.isFile()) return null;
		String cur = (String)comboBoxConfig.getSelectedItem();
		
		CsvImportParameter.CsvImportConfigElement conf = Param.getConfig(cur);
		conf.IgnoreHeader = Integer.valueOf(textFieldIgnoreHeader.getText());
		conf.DateColumn = Integer.valueOf(textFieldDateField.getText());
		conf.IntervalColumn = Integer.valueOf(textFieldTimeOffsetField.getText());
		conf.SampleRate = Integer.valueOf(textFieldSamplerate.getText() );
		
		
		int[] ids  =getTableId();
		for(int i=0;i<ids.length;i++){
			Object[] o = getTablevalue(ids[i]);
			int idx = Integer.valueOf((String)o[1]);
			double dd = Double.valueOf((String)o[2]);
			CsvImportParameter.CsvImportFieldElement ele =  new CsvImportParameter().new CsvImportFieldElement();
			ele.Chid=ids[i];
			ele.Column=idx;
			ele.Factor = dd;
			Param.setFieldElement(cur,ele);
		}
		tmp.setParameter(Param,cur);
		
		String sttime  = textFieldStartTime.getText();
		int interval   = Integer.valueOf(textFieldIntervalSec.getText());
		int intapo = comboBoxInterporation.getSelectedIndex();
		
		tmp.setParameter2(sttime,interval,intapo);
		
		
		return tmp.getImportData(f);
	}
	/*
	 * データをファイルに出力して返す。
	 */
	public String getImportDataAsFile(){
		setCursor((Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR )));
		ImportData data = getImportData();
		String ret = null;
		if(data == null){
			JOptionPane.showMessageDialog(this,"Error found in reading csv","Error",JOptionPane.ERROR_MESSAGE);
		}
		else{
			if(data.GetChCount() > 0){
				WinImporter imp = new WinImporter();
				imp.makeWinFile(OutDir, data);
				OutFile = OutDir;
				ret = OutDir;
			}
			else{
				JOptionPane.showMessageDialog(this,"Error found in reading csv / no data!","Error",JOptionPane.ERROR_MESSAGE);
			}
		}
		setCursor((Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR )));
		return ret;
	}
}
